//==========================================================  
// TextureFactory class - Handles tileSets and textures
//==========================================================

//==========================================================  
// Splits TileSets into texturesTiles and return them in an 
// array. Its dynamic so size can vary
//==========================================================
var splitTileSet = function (tileSets) {
    var texturePathsArray = [];
    
    for (var key in tileSets) {
        var tile = {
            path: tileSets[key].image,
            imageHeight: tileSets[key].imageheight,
            imageWidth: tileSets[key].imagewidth,
            tileHeight: tileSets[key].tileheight,
            tileWidth: tileSets[key].tilewidth,
            imageHeightCount: (tileSets[key].imageheight / tileSets[key].tileheight),
            imageWidthCount: (tileSets[key].imagewidth / tileSets[key].tilewidth),
            tileMargin: tileSets[key].margin,
            tileZOffset: tileSets[key].properties.zaxis,
        };
        texturePathsArray[key++] = tile;    
    }
    var tileSetsArray = createTextureArray(texturePathsArray);
    
    return tileSetsArray;
}

//==========================================================  
// Creates array with textures for tilemap
//==========================================================
function createTextureArray (fileNameArray) {

    var tileArray = [];
    var tileNr = 1;
    
    for (var i = 0; i < fileNameArray.length; i++)
    {              
        for (var j = 0; j < fileNameArray[i].imageHeightCount; j++)
        {
            for (var k = 0; k < fileNameArray[i].imageWidthCount; k++)
            {                       
                var crateImageParameters = {
                    src: fileNameArray[i].path,
                    mipmaps: true
                };
                
                tileArray[tileNr] = { 
                    texture: graphicsDevice.createTexture(crateImageParameters),
                    xCoord: fileNameArray[i].tileWidth * k,
                    yCoord: fileNameArray[i].tileHeight * j,
                    imageWidth: fileNameArray[i].tileWidth,
                    imageHeight: fileNameArray[i].tileHeight,
                    imageMargin: fileNameArray[i].tileMargin,
                    zOffset: parseInt(fileNameArray[i].tileZOffset),
                };
                
                tileNr++;
            }
        }        
    }    
    return tileArray;
};